package com.client.smartauction;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class BiddingActivity extends Activity {
	final String TAG = "BiddingActivity";

	final int SERVERPORT = 5000;
	final int UDPSERVERPORT = 5001;
	final int IMAGE_SERVERPOT = 5002;

	private String SERVERIP = "192.168.0.14";
	private ImageAsynk mImageAsynk;
	private UdpAsynk mUdpAysnk;

	private TcpSocket mTcpSocket;
	private UdpSocket mUdpSocket;
	private long mCurrentTime;
	private String mId;
	private String mPassWord;
	private Intent intent;

	private Product mCurrentProduct;

	private ImageView ac_PImage;
	private Button ac_BidBtn;
	private Button ac_QuitBtn;
	private EditText ac_Inputprice;
	private TextView ac_CurrentPrice;

	private TextView ac_Timer;
	private CountDownTimer mTimer;
	private JSONObject jsonobj;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photoview);

		intent = getIntent();
		String name = intent.getStringExtra("name");
		String price = intent.getStringExtra("price");
		String time = intent.getStringExtra("time");
		String des = intent.getStringExtra("des");
		SERVERIP = intent.getStringExtra("serverip");
		mId = intent.getStringExtra("ID");
		mPassWord = intent.getStringExtra("PassWord");
		mCurrentProduct = new Product(name, price, time, des);

		ac_Inputprice = (EditText) findViewById(R.id.bidPrice);
		ac_CurrentPrice = (TextView) findViewById(R.id.CurrentPrice);
		ac_PImage = (ImageView) findViewById(R.id.productImage);
		ac_Timer = (TextView) findViewById(R.id.timer);
		ac_BidBtn = (Button) findViewById(R.id.bidBtn);
		ac_QuitBtn = (Button) findViewById(R.id.bidQuit);
		ac_CurrentPrice.setText(mCurrentProduct.getInitPrice());

		ConnAsynk conn = new ConnAsynk();
		conn.execute();

		JSONObject jsonobj = new JSONObject();
		try {
			jsonobj.put("HEADER", "JOIN");
			jsonobj.put("ID", mId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		TcpSendAsynk mTcpAsynk = new TcpSendAsynk();
		mTcpAsynk.execute(jsonobj);

		mUdpAysnk = new UdpAsynk();
		mUdpAysnk.execute();

		Thread thread = new Thread(new Runnable() {
			private Socket mImSocket;
			private ServerSocket mImSerSocket;
			private Bitmap bm;
			
			public void run() {
				// TODO Auto-generated method stub
				try {
					mImSerSocket = new ServerSocket(IMAGE_SERVERPOT);
				} catch (IOException e) {
					Log.e(TAG, "Serversocket error");
					e.printStackTrace();
				}
				try {
					// bm = Bitmap.createBitmap(160, 120,
					// Bitmap.Config.ARGB_4444);
					mImSocket = mImSerSocket.accept();
					while (true) {
						BufferedInputStream input = new BufferedInputStream(
								mImSocket.getInputStream());
						// bm = Bitmap.createBitmap(160, 120,
						// Bitmap.Config.ARGB_4444);
						bm = BitmapFactory.decodeStream(input);
						Log.e(TAG, "시발새끼야 여긴가?");
						if (bm != null) {
							Log.d(TAG, "시발새끼야 여긴가?");
							Message msg = mHandlerImage.obtainMessage();
							msg.obj = bm;
							mHandlerImage.sendMessage(msg);
							// Thread.sleep(1000);
						}
					}
				} catch (IOException e) {
					Log.e(TAG, "Socket Accpet error");
					e.printStackTrace();
				}

			}
		});
		thread.start();

		// ImageAsynk mImageAsynk = new ImageAsynk();
		// mImageAsynk.execute();
	}

	final Handler mHandlerImage = new Handler() {

		public void handleMessage(Message msg) {
			Log.d(TAG, "핸드럴 십색끼야 시발새끼야 여긴가?");
			ac_PImage.setImageBitmap((Bitmap) msg.obj);
			ac_PImage.invalidate();
		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		ac_BidBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (Integer.parseInt(ac_CurrentPrice.getText().toString()) >= Integer
						.parseInt(ac_Inputprice.getText().toString()))
					Toast.makeText(getApplicationContext(),
							"This Price is now allowed", Toast.LENGTH_SHORT)
							.show();
				else {
					jsonobj = new JSONObject();
					try {
						jsonobj.put("HEADER", "PRICE");
						jsonobj.put("PRICE", ac_Inputprice.getText().toString());
						Thread thread = new Thread(new Runnable() {
							public void run() {
								// TODO Auto-generated method stub
								mTcpSocket.sendMsg(jsonobj);
							}
						});
						thread.start();

					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

			}
		});
		ac_QuitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				jsonobj = new JSONObject();
				try {
					jsonobj.put("HEADER", "QUIT");

				} catch (JSONException e) {
					e.printStackTrace();
				}

				Thread thread = new Thread(new Runnable() {
					public void run() {
						// TODO Auto-generated method stub
						mTcpSocket.sendMsg(jsonobj);
					}
				});
				thread.start();

				Intent intent = new Intent(BiddingActivity.this,
						MainActivity.class);
				startActivity(intent);
			}
		});

	}

	private class ConnAsynk extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mTcpSocket = new TcpSocket(SERVERIP, SERVERPORT);
			return null;
		}

	}

	private class TcpSendAsynk extends AsyncTask<JSONObject, Void, Void> {
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "방에 접속하였습니다.",
					Toast.LENGTH_SHORT).show();
			super.onPostExecute(result);
		}

		@Override
		protected synchronized Void doInBackground(JSONObject... params) {
			// TODO Auto-generated method stub
			mTcpSocket.sendMsg(params[0]);
			return null;
		}
	}

	private class UdpAsynk extends AsyncTask<Void, String, String> {
		private String result = "";
		private String price = "";
		private String user = "";

		@Override
		protected String doInBackground(Void... params) {

			mUdpSocket = new UdpSocket(UDPSERVERPORT);
			while (true) {
				result = mUdpSocket.Receive();
				if (result != "") {
					try {
						JSONObject obj = new JSONObject(result);

						if (obj.has("HEADER")) {
							String header = obj.getString("HEADER");
							if (header.equals("START")) {
								publishProgress("START");
							} else if (header.equals("REJECT")) {
								price = "0";
								publishProgress(price);
							} else if (header.equals("PRICE")) {
								price = obj.getString("PRICE");
								publishProgress(price);
							} else if (header.equals("FINISH")) {
								price = obj.getString("PRICE");
								user = obj.getString("USER");
								return price + "로" + user + "분께서 낙찰 되셨습니다.";
							}
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			if (values[0] == "START") {
				mTimer = new CountDownTimer(60000, 1000) {
					public void onTick(long millisUntilFinished) {
						long min = millisUntilFinished / 60000;
						long sec = (millisUntilFinished % 60000) / 1000;
						ac_Timer.setText(min + ":" + sec);
						mCurrentTime = millisUntilFinished;
					}

					@Override
					public void onFinish() {
						// TODO Auto-generated method stub
						ac_Timer.setText("done!");
					}
				}.start();

			} else if (Integer.parseInt(values[0]) > Integer
					.parseInt(ac_CurrentPrice.getText().toString())) {
				ac_CurrentPrice.setText(values[0]);
				if (mCurrentTime / 1000 < 20) {
					mTimer.cancel();
					mTimer = new CountDownTimer(20000, 1000) {
						public void onTick(long millisUntilFinished) {
							long min = millisUntilFinished / 60000;
							long sec = (millisUntilFinished % 60000) / 1000;
							ac_Timer.setText(min + ":" + sec);
							mCurrentTime = millisUntilFinished;
						}

						@Override
						public void onFinish() {
							// TODO Auto-generated method stub
							ac_Timer.setText("done!");
						}
					}.start();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						"This Price is now allowed", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT)
					.show();
			super.onPostExecute(result);

		}

	}

	private class ImageAsynk extends AsyncTask<Void, Bitmap, Void> {
		private Bitmap bm;
		private Socket mImSocket;
		private ServerSocket mImSerSocket;

		@Override
		protected Void doInBackground(Void... arg) {
			try {
				mImSerSocket = new ServerSocket(IMAGE_SERVERPOT);
			} catch (IOException e) {
				Log.e(TAG, "Serversocket error");
				e.printStackTrace();
			}

			try {
				mImSocket = mImSerSocket.accept();
				while (true) {
					bm = BitmapFactory.decodeStream(mImSocket.getInputStream());
					if (bm != null)
						publishProgress(bm);
				}
			} catch (IOException e) {
				Log.e(TAG, "Socket Accpet error");
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Bitmap... values) {

			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}
	}

}
